package com.example.simplesvc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;

@Service
public class MySpringServiceWithThread implements DisposableBean , InitializingBean {

    private Logger log = LoggerFactory.getLogger(MySpringServiceWithThread.class);


    private Thread thread ;

    private volatile boolean serverStopping = false;


    public MySpringServiceWithThread() {
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 模拟一个后台检查任务
                while(true) {
                    if(serverStopping) {
                        //服务器正在退出
                        log.debug("服务器关闭中，退出执行");
                        return;
                    }

                    log.debug("后台进程检查程序，模拟流式消费MQ消息");


                    //1 sleep，wait，join等操作 可能会引起因为中断引起 InterruptedException
                    try {
                        Thread.sleep(5000);
                    }catch (InterruptedException e) {
                        log.debug("线程被中断，退出执行");
                        return;
                    }

                    //2 InterruptibleChannel 网络通信操作，可能会引起因为中断引起 ClosedByInterruptException
//                    try {
//                        InetSocketAddress addr = new InetSocketAddress("www.163.com",80);
//                        //建立连接时可如果线程被中断，就会抛出ClosedByInterruptException
//                        SocketChannel ch = SocketChannel.open(addr);
//                        ByteBuffer bb = ByteBuffer.allocate(4096);
//                        //读取数据时可如果线程被中断，就会抛出ClosedByInterruptException
//                        ch.read(bb);
//                        bb.flip();
//                        log.info("received data " + new String( bb.array()));
//                    }catch (ClosedByInterruptException e) {
//                        log.info("线程被中断，退出执行");
//                        return;
//                    }catch (Exception e) {
//                        log.error("通信失败", e);
//                    }

                    //3 检查线程状态，若处于中断状态，退出执行
                    if(Thread.currentThread().isInterrupted()) {
                        log.debug("线程被中断，退出执行");
                        return;
                    }

                }
            }
        });
    }



    @Override
    public void afterPropertiesSet()  {
            thread.start();
    }




    @Override
    public void destroy()  {

        this.serverStopping = true;
        // 感知tomcat正在关闭，中断线程执行
        try {
            thread.interrupt();
        }catch (Exception e) {

        }
    }


}
